package com.bskms.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.bskms.bean.Course;
import com.bskms.mapper.CourseMapper;
import com.bskms.service.CourseNotificationService;
import com.bskms.service.CourseReminderService;

@Service
public class CourseReminderServiceImpl implements CourseReminderService {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseReminderServiceImpl.class);
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private CourseNotificationService courseNotificationService;

    /**
     * 每分钟检查一次，发送课程提醒
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkAndSendCourseReminders() {
        try {
            List<Course> courses = getCoursesNeedReminder();
            
            for (Course course : courses) {
                try {
                    logger.info("开始发送课程提醒，课程: {}, 班级: {}", course.getName(), course.getCname());
                    boolean result = courseNotificationService.sendAutoCourseReminder(course);
                    logger.info("课程提醒发送完成，课程: {}, 结果: {}", course.getName(), result ? "成功" : "失败");
                } catch (Exception e) {
                    logger.error("发送课程提醒异常，课程ID: {}, 异常: {}", course.getId(), e.getMessage(), e);
                }
            }
            
            if (!courses.isEmpty()) {
                logger.info("本次检查共处理 {} 个课程的提醒发送", courses.size());
            }
            
        } catch (Exception e) {
            logger.error("检查课程提醒异常", e);
        }
    }

    @Override
    public List<Course> getCoursesNeedReminder() {
        try {
            // 获取当前时间
            Date now = new Date();
            
            // 计算10分钟后的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.MINUTE, 10);
            Date reminderTime = calendar.getTime();
            
            // 格式化时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowStr = sdf.format(now);
            String reminderTimeStr = sdf.format(reminderTime);
            
            logger.debug("检查课程提醒，当前时间: {}, 提醒时间范围: {} - {}", nowStr, nowStr, reminderTimeStr);
            
            // 查询需要发送提醒的课程
            List<Course> courses = courseMapper.getCoursesNeedReminder(nowStr, reminderTimeStr);
            
            logger.debug("找到 {} 个需要发送提醒的课程", courses.size());
            
            return courses;
            
        } catch (Exception e) {
            logger.error("获取需要提醒的课程异常", e);
            return Collections.emptyList();
        }
    }
}
